<template>
    <div>
         <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>Api列表</el-breadcrumb-item>
        </el-breadcrumb>
         <!-- 卡片视图 -->
         <el-card>
            <!-- 搜索 添加 -->
            <el-row :gutter="20">
                <el-col :span="3" style="padding-right: 0">
                    <el-select v-model="queryInfo.keyword" placeholder="请选择">
                        <el-option label="描述" value="description"></el-option>
                        <el-option label="路径" value="path"></el-option>
                        <el-option label="api分组" value="api_group"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="6">
                    <el-select v-if="queryInfo.keyword === 'api_group'" v-model="queryInfo.query" placeholder="请选择">
                        <el-option label="请选择" value=""></el-option>
                        <el-option v-for="item in ApiGroupList" :key="item" :label="item+'组'" :value="item"></el-option>
                    </el-select>
                     <el-input v-else placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getApiList"></el-input>
                </el-col>
                <el-col :span="2"><el-button type="text" style="color: black">请求方法</el-button></el-col>
                <el-col :span="5">
                     <el-select v-model="queryInfo.method" placeholder="请选择">
                        <el-option label="请选择" value=""></el-option>
                        <el-option label="创建（POST）" value="POST"></el-option>
                        <el-option label="删除（DELETE）" value="DELETE"></el-option>
                        <el-option label="修改（PUT）" value="PUT"></el-option>
                        <el-option label="查看（GET）" value="GET"></el-option>
                    </el-select>
                </el-col>
                <el-col :span="3">
                    <el-button type="primary" icon="el-icon-search" @click="getApiList">查询</el-button>
                </el-col>
                <el-col :span="2" style="float: right">
                    <el-button type="primary" style="float: right;margin-right: 40px;" @click="showAddApiDialog">添加Api</el-button>
                </el-col>
            </el-row>
             <el-table 
                ref="apiTable"
                v-loading="loading"
                element-loading-text="拼命加载中"
                element-loading-spinner="el-icon-loading"
                element-loading-background="rgba(0, 0, 0, 0.8)"
                :data="apiList"
                header-row-class-name="table_header" 
                :header-cell-style="table_header"
                border 
                stripe
                >
                 <el-table-column type="index" label="序号" width="100px" align="center"></el-table-column>
                 <el-table-column label="Api路径" prop="path" align="center" width="250px"></el-table-column>
                 <el-table-column label="请求方法" prop="method" align="center">
                     <template slot-scope="scope">
                         {{scope.row.method}}&nbsp;
                        <el-tag v-if="scope.row.method === 'POST'" type="success" effect="dark" size="small">创建</el-tag>
                        <el-tag v-else-if="scope.row.method === 'PUT'" type="warning" effect="dark" size="small">更新</el-tag>
                        <el-tag v-else-if="scope.row.method === 'GET'" type="primary" effect="dark" size="small">查看</el-tag>
                        <el-tag v-else type="danger" effect="dark" size="small">删除</el-tag>
                     </template>
                 </el-table-column>
                 <el-table-column label="Api分组" prop="apiGroup" align="center" width="100px"></el-table-column>
                 <el-table-column label="Api描述" prop="description" align="center"></el-table-column>
                 <el-table-column label="操作" align="center" width="150px">
                    <template slot-scope="scope">
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="编辑Api"
                        :enterable="false"
                        placement="top"
                        >
                            <el-button
                            type="primary"
                            icon="el-icon-edit"
                            size="mini"
                            circle
                            @click="showEditApiDialog(scope.row)"
                            ></el-button>
                        </el-tooltip>
                        <el-tooltip
                        class="item"
                        effect="dark"
                        content="删除Api"
                        :enterable="false"
                        placement="top"
                        >
                            <el-button
                            type="danger"
                            icon="el-icon-delete"
                            size="mini"
                            circle
                            @click="removeApiById(scope.row.ID, scope.row.description)"
                            ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
             </el-table>
              <!-- 分页区域 -->
            <div class="pager-box">
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageNum"
                    :page-sizes="[2, 5, 10, 15]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    prev-text="上一页"
                    next-text="下一页"
                    :total="total"
                    background
                    hide-on-single-page
                ></el-pagination>
            </div>
         </el-card>

         <el-dialog 
            :close-on-click-modal="false"
            :title="Dialog_title"
            :visible.sync="ApiDialogVisible"
            width="35%"
             @close="resetForm('ApiFormRef')">
            <el-form
                :model="ApiForm"
                :rules="ApiFormRules"
                ref="ApiFormRef"
                label-width="100px"
            >
                <el-form-item label="Api描述：" prop="description">
                    <el-input v-model="ApiForm.description"></el-input>
                </el-form-item>
                <el-form-item label="Api路径：" prop="path">
                    <el-input v-model="ApiForm.path"></el-input>
                </el-form-item>
                <el-form-item label="请求方法：" prop="method">
                    <el-select v-model="ApiForm.method" placeholder="请选择">
                        <el-option label="创建（POST）" value="POST"></el-option>
                        <el-option label="删除（DELETE）" value="DELETE"></el-option>
                        <el-option label="修改（PUT）" value="PUT"></el-option>
                        <el-option label="查看（GET）" value="GET"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="Api分组：" prop="apiGroup">
                    <el-input v-model="ApiForm.apiGroup"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="ApiDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddOrEditApi">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
        // 权限列表
            queryInfo: {
                query: '',
                // 当前页数
                pageNum: 1,
                // 每页显示多少数据
                pageSize: 10,
                method: '',
                keyword: 'path',
            },
            loading: true,
            apiList: [],
            ApiGroupList: [],
            total: 0,
            Dialog_title: '',
            Dialog_state: '',
            ApiDialogVisible: false,
            ApiForm: {},
            ApiFormRules: {
                path: [
                    { required: true, message: '请输入Api路径', trigger: 'blur' }
                ],
                method: [
                    { required: true, message: '请输入请求方法', trigger: 'blur' }
                ],
                description: [
                    { required: true, message: '请输入Api描述', trigger: 'blur' }
                ]
            },
        }
    },
    created () {
        this.getApiList();
        this.getApiGroup();
    },
    methods: {
        table_header(row, column, rowIndex, columnIndex){
            return 'background-color: #409EFF; color: white; font-size: 15px;'
        },
          // 监听 pagesize改变的事件
        handleSizeChange (newSize) {
            // console.log(newSize)
            this.queryInfo.pageSize = newSize
            this.getApiList()
        },
        // 监听 页码值 改变事件
        handleCurrentChange (newSize) {
            this.queryInfo.pageNum = newSize;
            this.getApiList();
        },
        async getApiGroup(){
          const {data: res, status: status} = await this.axios.get('api/getApiGroup');
          if (status !== 200) return this.$message.error("获取Api分组失败");
          this.ApiGroupList = res.data;
        },
        async getApiList () {
            var v1 = this;
            const { data: res, status: status } = await this.axios.get('api/getApiList', {params: v1.queryInfo});
            if (status !== 200) {
                return this.$message.error('获取权限列表失败！')
            }
            this.apiList = res.data.apis;
            this.total = res.data.total;
            this.loading = false
        },
         // 添加操作
        showAddApiDialog () {
            this.Dialog_state = 'add';
            this.Dialog_title = '添加Api';
            this.ApiDialogVisible = true;
        },
        // 显示编辑对话框
        showEditApiDialog (api) {
            this.ApiForm = JSON.parse(JSON.stringify(api));
            this.Dialog_state = 'edit';
            this.Dialog_title = '编辑Api';
            this.ApiDialogVisible = true;
        },
        resetForm(formName) {
            this.ApiForm = {};
            this.$refs[formName].resetFields();
        },
        // 添加分类
        AddOrEditApi () {
            this.$refs.ApiFormRef.validate(async valid => {
                if (!valid) return;
                if (this.Dialog_state === 'add') {
                    const {data: res, status: status} = await this.axios.post('api/addApi', this.ApiForm);
                    if (status !== 200) {
                        return this.$message.error('添加分类失败！')
                    }
                    this.$message.success('添加分类成功！');
                }else {
                    const { data: res, status: status } = await this.axios.put('api/updateApi', this.ApiForm);
                    if (status !== 200) return this.$message.error('更新Api失败！');
                    this.$message.success('更新Api成功！');
                }
                this.getApiList();
                this.ApiDialogVisible = false;
            })
        },

        // 删除Api
        async removeApiById(id, name) {
            const confirmResult = await this.$confirm('此操作将永久删除Api ' + name + ', 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err);
            if (confirmResult !== 'confirm') { return this.$message.info('已取消删除！') }
            const { data: res, status: status } = await this.axios.delete('api/deleteApi', {params: {"id": id}})
            if (status !== 200) { return this.$message.error('删除Api失败！') }
            this.$message.success('删除Api成功！');
            this.getApiList();
        },
    },
}
</script>
<style lang="less" scoped>
</style>